requirejs(['jquery', 'Util', 'bootstrap', 'summerNote', 'summerZhCN'], function ($, Util) {

    console.log('post-console');

    // 初始化summernote
    $('#summernote').summernote({
        lang: 'zh-CN',
        placeholder: 'write here...',
        height: 300,
        minHeight: null,
        maxHeight: null,
        focus: false,
        onImageUpload: function (files, editor, welEditable) {
            sendFile(files[0], editor, welEditable);
        }
    });

    function sendFile(file, editor, welEditable) {
        data = new FormData();
        data.append("file", file);
        $.ajax({
            data: data,
            type: "POST",
            url: "/admin/post_upload/",
            cache: false,
            contentType: false,
            processData: false,
            success: function (url) {
                editor.insertImage(welEditable, url);
            }
        });
    }

    // 标签点击
    $('.tag-item').on('click', function (e) {
        e.preventDefault();
        $(this).toggleClass('active');
    });

    // 修改保存按钮点击
    $('#post-save-btn').on('click', function () {

        if (!$('#post-title').val()) {
            Util.Alert('新增失败，请输入标题...', 1);
            return;
        }

        if (!$('#summernote').summernote('code')) {
            Util.Alert('新增失败，请输入内容...', 1);
            return;
        }

		var post_id = $(this).attr('data-id');

        var tags = [];
        $('.tag-item').each(function (index, node) {
            if ($(node).hasClass('active')) {
                tags.push($(node).attr('data-id'));
            }
        });

        (tags.length === 0) && (tags = '');

        $.post('/admin/update_post/', {
			id : post_id,
            title: $('#post-title').val(),
            cat: $('#post-cat').val(),
            tag: tags,
            content: $('#summernote').summernote('code')
        }, function (ret) {
            if (ret)
                Util.Alert('修改成功...', 1,function(){
					window.location.href="/admin/post_config";
				});
        });

    });

    // 放弃按钮点击
    $('#giveup-btn').on('click', function () {
		window.history.go(-1);
    });

});
